package com.atguigu.gmall.item.config;

import com.atguigu.gmall.item.config.thread.ItemThreadPoolProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author 钟涛
 * @version 1.0
 * @description: TODO
 * @date 2021/12/10 9:41
 */
//@Import(RedissonConfig.class)
@Configuration
@EnableConfigurationProperties(ItemThreadPoolProperties.class)
@EnableFeignClients(basePackages = {"com.atguigu.gmall.feign.product","com.atguigu.gmall.feign.list"})
public class ItemApplicationConfig {
    /**
     * 创建一个执行异步任务的线程池
     */
    @Bean
    public ThreadPoolExecutor threadPoolExecutor(ItemThreadPoolProperties properties){

        return new ThreadPoolExecutor(properties.getCorePoolSize()
                ,properties.getMaximumPoolSize(),
                properties.getKeepAliveTime(),
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(properties.getWorkQueueSize()),
                new ItemThreadFactory(properties.getThreadPoolName()),
                new ThreadPoolExecutor.CallerRunsPolicy());//提交不上去就同步方式运行
    }

   class ItemThreadFactory implements ThreadFactory{
        private String threadPoolName;
        public ItemThreadFactory(String threadPoolName){
            this.threadPoolName = threadPoolName;
        }
       int count = 0;
       @Override
       public Thread newThread(Runnable r) {
           Thread thread = new Thread(r);
           thread.setName(this.threadPoolName + ": Thread["+ (count++)+"]");
           return thread;
       }
   }

}
